define(["../../js/request.js"], function(requestHub) {
	var scope = this,
		$$ = bowlder,
	  	widget = scope.$widget,
	  	roles = widget.roles;

	scope.state = {
		uploading: false,
		dragenter: false,
		showWatermarkPanel: false,
		currentWatermarkId: 0,
		currentWatermarkPos: '1'
	};

	var uploadRole;
	var currentWatermark = {
		id: 0,
		watername: '无水印'
	};

	scope.completed = 0;
	scope.picList = [];
	scope.progress_completed = 0;
	
	var fileBtn;
	var fileList = [];
	function fileChange(files) {
		var newFileList = files;
		for (var i=0;i<newFileList.length;i++) {
			fileList.push(files[i]);
		}
		for (var i=0; i<newFileList.length; i++) {
			var reader = new FileReader();
			var f = newFileList[i];
			reader.onload = (function(theFile) {
				return function(e) {
					scope.picList.push({
						src: e.target.result,
						name: theFile.name,
						type: theFile.type,
						size: theFile.size
					});
					scope.$refresh();
				}
			})(f);
			reader.readAsDataURL(f);
		}
	}

	function resetStatus() {
		scope.state.uploading = false;
		scope.completed = 0;
		scope.progressCompleted = 0;
		fileList = [];
		scope.picList = [];
		scope.$refresh();
	}

	function postPic(pic, i) {
		var formData = new FormData();
		formData.append('file', pic);
		formData.append('desc', pic.name);
		formData.append('setid', parseInt(scope.state.extendInfo.setId, 10));
		formData.append('title', pic.name.replace(/\.\w+$/, ''));
		formData.append('topicid', scope.state.id);
		if (scope.state.currentWatermarkId !== 0) {
			formData.append('watername', currentWatermark.watercode);
			formData.append('position', watermarkMap[scope.state.currentWatermarkPos]);
		}
		var xhr = new XMLHttpRequest();
		xhr.withCredentials = true;
	    xhr.open("POST", requestHub.baseUrl + '/photo/'+scope.state.id.substr(4, 4)+'/upload');
	    xhr.onreadystatechange = function () {
	        if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
	        	scope.completed++;
	        	scope.progressCompleted = (scope.picList.length > 0 ? scope.completed/scope.picList.length : 0)*550;
	        	scope.$refresh();
	        	if (scope.completed === fileList.length) {
	        		setTimeout(function() {
						alert('全部图片上传成功，共' + fileList.length + '张');
	        			resetStatus();
	        			$$.emit('photosetList.refresh.'+scope.state.id, scope.state.id);
	        			$$.emit('tab.replaceTab', {
	        				id: scope.state.id,
	        				uuid: 'photosetDetail_' + scope.state.id + '_' + scope.state.extendInfo.setId,
	        				from: scope.state.uuid,
	        				type: 'photosetDetail',
	        				name: '图集详情-' + scope.state.extendInfo.setName,
	        				extendInfo: {
								photoset: {
									setname: scope.state.extendInfo.setName,
									setid: scope.state.extendInfo.setId,
									topicid: scope.state.id
								}
							}
	        			});
	        		}, 1000);
	        		
	        	}
	        }
	    };
	    xhr.send(formData);
	};

	scope.setWatermark = function() {
		scope.state.showWatermarkPanel = true;
	};

	scope.closeWatermarkPanel = function() {
		scope.state.showWatermarkPanel = false;
		scope.state.currentWatermarkPos = '1';
		scope.state.currentWatermarkId = 0;
	};

	scope.confirmWatermark = function() {
		scope.state.showWatermarkPanel = false;
	};

	scope.removePic = function(pic, index) {
		scope.picList.splice(index, 1);
		fileList.splice(index, 1);
	};

	scope.selectImg = function() {
		fileBtn.trigger('click');
	};

	scope.uploadImg = function() {
		if (scope.picList.length === 0) {
			alert('请选择图片');
			return;
		}
		scope.state.uploading = true;
		$$.each(fileList, function(file, index) {
			postPic(file, index);
		});
	};

	scope.cancelUpload = function() {
		scope.state.uploading = false;
	};

	requestHub.service('getChannelWatermarkList', {
		method: 'get',
		urlParams: {
			channelid: scope.protoUserInfo.currentChannel.channelId
		},
		log: 1
	})
	.then(function(res) {
		res.data.unshift(currentWatermark);
		scope.watermarkList = res.data;
		scope.$refresh();
	
	}, function(err) {
		console.error(err);
	});

	var watermarkMap = {
		'1': 'northwest',
		'2': 'north',
		'3': 'northeast',
		'4': 'west',
		'5': 'center',
		'6': 'east',
		'7': 'southwest',
		'8': 'south',
		'9': 'southeast'
	};

	scope.chooseMark = function(index) {
		currentWatermark = scope.watermarkList[index];
		scope.state.currentWatermarkId = currentWatermark.id;
	};
	scope.choosePos = function(index) {
		scope.state.currentWatermarkPos = index;
	};

	scope.init = function(widget) {
		console.log('uploadimg ', scope.state, requestHub.baseUrl);
		fileBtn = roles['selectFile'];
		uploadRole = roles['upload'];
		
		fileBtn.bind('change', function(e) {
			fileChange(e.target.files);
		});

		uploadRole.bind('dragenter', function() {
			scope.state.dragenter = true;
			scope.$refresh();
		});

		uploadRole.bind('dragover', function(e) {
			e.preventDefault();
		});

		uploadRole.bind('dragleave',function(e) {
			scope.state.dragenter = false;
			scope.$refresh();
		});

		uploadRole.bind('drop', function(e) {
			e.preventDefault();
			scope.state.dragenter = false;
			scope.$refresh();
			fileChange(e.dataTransfer.files);
		});

		scope.info = {
			topicId: scope.state.id,
			type: scope.state.type
		};
	};
	
});